# -*- coding: utf-8 -*-  # 添加此行

'''
 全部路由地址路由路径集合


'''

from fastapi import APIRouter
from fastapi import FastAPI, Depends, HTTPException, Query
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from database.database import SessionLocal, engine
from models import user as user_model
from schemas import user as user_schema
from crud import user as user_crud
from contextlib import asynccontextmanager
from typing import Optional

#添加路由前缀
ApiRouter = APIRouter(prefix="/v1",tags = ['api 路由'])

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@ApiRouter.get("/user-management", summary="用户管理页面")
async def user_management_page():
    """用户管理HTML页面"""
    return FileResponse("static/user_management.html", media_type="text/html")

@ApiRouter.post("/UserRegister", summary="用户注册接口")
async def user_register_endpoint(user: user_schema.UserRegister, db: Session = Depends(get_db)):
    """用户注册接口"""
    try:
        result = user_crud.register_user(db, user)
        return result
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"注册失败: {str(e)}")

@ApiRouter.post("/UserLogin", summary="用户登录接口")
async def user_login_endpoint(user: user_schema.UserLogin, db: Session = Depends(get_db)):
    """用户登录接口"""
    try:
        db_user = user_crud.login_user(db, user)
        return user_schema.UserLoginResponse(
            id=db_user.id,
            username=db_user.username,
            phone=db_user.phone,
            email=db_user.email,
            message="登录成功"
        )
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"登录失败: {str(e)}")

@ApiRouter.get('/')
async def home(num : int):
    return {"num":num}

@ApiRouter.post("/users/", response_model=user_schema.UserOut)
def create_user(user: user_schema.UserCreate, db: Session = Depends(get_db)):
    return user_crud.create_user(db, user)

@ApiRouter.get("/users/{user_id}", response_model=user_schema.UserOut)
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = user_crud.get_user(db, user_id)
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

@ApiRouter.get("/users/", response_model=list[user_schema.UserOut])
def read_users(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    users = user_crud.get_users(db, skip=skip, limit=limit)
    return users

@ApiRouter.put("/users/{user_id}", response_model=user_schema.UserOut)
def update_user(
    user_id: int, 
    phone: Optional[str] = Query(None, description="新手机号"),
    email: Optional[str] = Query(None, description="新邮箱"),
    db: Session = Depends(get_db)
):
    """更新用户信息 - 通过URL参数"""
    if not phone and not email:
        raise HTTPException(status_code=400, detail="至少需要提供一个要更新的字段")
    
    db_user = user_crud.update_user(db, user_id, phone, email)
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

@ApiRouter.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
    success = user_crud.delete_user(db, user_id)
    if not success:
        raise HTTPException(status_code=404, detail="User not found")
    return {"msg": "User deleted successfully"}